/************************************************************************
* client.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"

#include "client.h"
#include "meshgen.h"
#include "map.h"

static struct {
	uint8_t issingle;
} client_data = {
	0
};

static int client_connect_defaults()
{
	meshgen_init();
	/* TODO: map meshgen triggers, etc */
	map_trigger_add(MAP_TRIGGER_LOADED,meshgen_add_chunk);
	map_trigger_add(MAP_TRIGGER_UPDATE,meshgen_add_chunk);
	map_trigger_add(MAP_TRIGGER_UNLOAD,meshgen_free_chunk);
	return 0;
}

static int client_postconnect()
{
	pos_t p;
	int x;
	int z;

	/* TODO: offset this to where the player actually is */

	for (x=-128; x<129; x+=32) {
		for (z=-128; z<129; z+=32) {
			p.x = x;
			p.y = 0;
			p.z = z;
			mapgen_request(&p);
		}
	}

	return 0;
}

/* initialise the client */
int client_init()
{
	return 0;
}

/* connect to/start a singleplayer game */
int client_connect_singleplayer(char* world)
{
	client_data.issingle = 1;
	client_state(VLSTATE_PLAY);

	client_connect_defaults();

	/* TODO: map triggers */

	if (world_init(world)) {
		client_state(VLSTATE_MENU);
		return 1;
	}

	return client_postconnect();
}

/* connect to a multiplayer server */
int client_connect_multiplayer(char* address, char* port)
{
	client_data.issingle = 0;
	client_state(VLSTATE_PLAY);

	client_connect_defaults();

	/* TODO: map triggers */

	/* TODO: connect to a server */

	client_state(VLSTATE_MENU);
	return 1;
}

/* disconnect from a game */
void client_disconnect()
{
	if (client_data.issingle)
		world_exit();

	meshgen_exit();

	client_data.issingle = 0;
}
